﻿#include "page1.h"
#include "ErrorDialog.h"
#include "databaseManager.h"
#include <QPixmap>
#include <QPalette>
#include <QFont>
#include "ConnectionDialog.h"

Page1::Page1(QWidget* parent) : QWidget(parent)
{
    setFixedSize(1280, 720);
    setStyleSheet(
                "QLineEdit, QDateEdit {"
                "  font-size: 18px;"
                "  font-weight: bold;"
                "  border: 2px solid #E0E0E0;"
                "  border-radius: 20px;"
                "  padding: 10px;"
                "  color: black;"
                "}"
                "QPushButton {"
                "  font-size: 18px;"
                "  font-weight: bold;"
                "  border: 2px solid #E0E0E0;"
                "  border-radius: 20px;"
                "  padding: 10px;"
                "  background-color: lightblue;"
                "  color: white;"
                "}");

    // 设置背景图片
    QPixmap background(":new/prefix1/login.png");
    QPalette palette;
    palette.setBrush(QPalette::Window, background.scaled(size()));
    setAutoFillBackground(true);
    setPalette(palette);

    // 创建字体对象
    QFont font;
    font.setPointSize(12);  // 设置字体大小为12点（根据比例调整）

    // "选择连接"按钮
    connectionButton = new QPushButton(u8"选择连接", this);
    connectionButton->setFont(font);
    connectionButton->setStyleSheet("font-size: 24px;");
    connectionButton->setGeometry(50, 650, 177, 50);

    // 连接"选择连接"按钮点击事件
    connect(connectionButton, &QPushButton::clicked, this, &Page1::openConnectionDialog);

    accountEdit = new QLineEdit(this);
    accountEdit->setPlaceholderText("请输入账号");
    accountEdit->setGeometry(414, 399, 492, 52);

    passwordEdit = new QLineEdit(this);
    passwordEdit->setPlaceholderText("请输入密码");
    passwordEdit->setGeometry(414, 463, 492, 52);
    passwordEdit->setEchoMode(QLineEdit::Password);

    // 显示/隐藏密码按钮
    togglePasswordButton = new QPushButton(this);
    togglePasswordButton->setGeometry(860, 470, 39, 39);
    togglePasswordButton->setCheckable(true);

    // 设置按钮图标
    QPixmap eyePixmap(":new/prefix1/eye_open.jpg");
    QPixmap eyeClosedPixmap(":new/prefix1/eye_close.jpg");
    togglePasswordButton->setIcon(QIcon(eyeClosedPixmap));
    togglePasswordButton->setIconSize(QSize(39, 39));

    // 连接按钮切换事件
    connect(togglePasswordButton, &QPushButton::toggled, this, [=](bool checked) {
        if (checked) {
            passwordEdit->setEchoMode(QLineEdit::Normal);
            togglePasswordButton->setIcon(QIcon(eyePixmap));
        } else {
            passwordEdit->setEchoMode(QLineEdit::Password);
            togglePasswordButton->setIcon(QIcon(eyeClosedPixmap));
        }
    });

    adminRadioButton = new QRadioButton(u8"管理员", this);
    adminRadioButton->setFont(font);
    adminRadioButton->setStyleSheet("color: black;");
    adminRadioButton->setGeometry(296, 530, 177, 26);

    salesRadioButton = new QRadioButton(u8"销售管理员", this);
    salesRadioButton->setFont(font);
    salesRadioButton->setStyleSheet("color: black;");
    salesRadioButton->setGeometry(444, 530, 177, 26);

    warehouseRadioButton = new QRadioButton(u8"库存管理员", this);
    warehouseRadioButton->setFont(font);
    warehouseRadioButton->setStyleSheet("color: black;");
    warehouseRadioButton->setGeometry(628, 530, 177, 26);

    financeRadioButton = new QRadioButton(u8"财务管理员", this);
    financeRadioButton->setFont(font);
    financeRadioButton->setStyleSheet("color: black;");
    financeRadioButton->setGeometry(812, 530, 177, 26);

    // 将单选按钮添加到按钮组中
    roleGroup = new QButtonGroup(this);
    roleGroup->addButton(adminRadioButton);
    roleGroup->addButton(salesRadioButton);
    roleGroup->addButton(warehouseRadioButton);
    roleGroup->addButton(financeRadioButton);

    loginButton = new QPushButton(u8"登录", this);
    loginButton->setFont(font);
    loginButton->setStyleSheet("font-size: 24px;");
    loginButton->setGeometry(550, 574, 177, 50);

    // 登录信息错误连接信号传递
    connect(this, &Page1::errloading, this, &Page1::showErrorDialog);

    // 连接登录按钮点击事件
//auto loginFunction = [this]() {
//        if (validateCredentials()) {
//            emit nextPageRequested();
//            if (salesRadioButton->isChecked()) {
//                emit salesLogin();
//            } else if (adminRadioButton->isChecked()) {
//                emit adminLogin();
//            } else if (warehouseRadioButton->isChecked()) {
//                emit warehouseLogin();
//            } else if (financeRadioButton->isChecked()) {
//                emit financeLogin();
//            }
//        } else {
//            errloadingFunc();
//        }
//    };

    connect(loginButton, &QPushButton::clicked, this, &Page1::onLoginButtonClicked);

    // 连接文本框和单选按钮状态变化的信号到槽函数
    connect(accountEdit, &QLineEdit::textChanged, this, &Page1::updateLoginButtonState);
    connect(passwordEdit, &QLineEdit::textChanged, this, &Page1::updateLoginButtonState);
    connect(adminRadioButton, &QRadioButton::toggled, this, &Page1::updateLoginButtonState);
    connect(salesRadioButton, &QRadioButton::toggled, this, &Page1::updateLoginButtonState);
    connect(warehouseRadioButton, &QRadioButton::toggled, this, &Page1::updateLoginButtonState);
    connect(financeRadioButton, &QRadioButton::toggled, this, &Page1::updateLoginButtonState);

    // 连接 Enter 键按下信号
    connect(accountEdit, &QLineEdit::returnPressed, this, &Page1::onLoginButtonClicked);
    connect(passwordEdit, &QLineEdit::returnPressed, this, &Page1::onLoginButtonClicked);

    // 初始化时检查登录按钮的状态
    updateLoginButtonState();
};

void Page1::onLoginButtonClicked() {
    if (validateCredentials()) {
        emit nextPageRequested();
        if (salesRadioButton->isChecked()) {
            emit salesLogin();
        } else if (adminRadioButton->isChecked()) {
            emit adminLogin();
        } else if (warehouseRadioButton->isChecked()) {
            emit warehouseLogin();
        } else if (financeRadioButton->isChecked()) {
            emit financeLogin();
        }
        clearInputFields();
    } else {
        errloadingFunc();
    }
}


void Page1::errloadingFunc() {
    emit errloading();
}

void Page1::showErrorDialog() {
    ErrorDialog errorDialog("账号、密码、身份选择有误", this);
    errorDialog.setFontSize(16);  // 调整文字大小
    errorDialog.setDialogSize(400, 200);  // 调整窗口大小
    setStyleSheet("QPushButton {"
                  "  font-size: 18px;"
                  "  font-weight: bold;"
                  "  border: 2px solid #E0E0E0;"
                  "  border-radius: 20px;"
                  "  padding: 10px;"
                  "  background-color: #0093D1;"
                  "  color: white;"
                  "}");
    errorDialog.exec();
}

void Page1::updateLoginButtonState() {
    // 检查账号输入框是否有输入
    bool isAccountFilled = !accountEdit->text().isEmpty();
    // 检查密码输入框是否有输入
    bool isPasswordFilled = !passwordEdit->text().isEmpty();
    // 检查是否有一个身份被选中
    bool isRoleSelected = adminRadioButton->isChecked() || salesRadioButton->isChecked() ||
            warehouseRadioButton->isChecked() || financeRadioButton->isChecked();

    // 如果账号和密码都有输入且有身份被选中，则启用登录按钮，否则禁用它
   bool isLoginEnabled = isAccountFilled && isPasswordFilled && isRoleSelected;
    loginButton->setEnabled(isLoginEnabled);
    loginButton->setStyleSheet(isLoginEnabled ?
        "QPushButton {"
        "  font-size: 18px;"
        "  font-weight: bold;"
        "  border: 2px solid #E0E0E0;"
        "  border-radius: 20px;"
        "  padding: 10px;"
        "  background-color: #0093D1;"
        "  color: white;"
        "}" :
        "QPushButton {"
        "  font-size: 18px;"
        "  font-weight: bold;"
        "  border: 2px solid #E0E0E0;"
        "  border-radius: 20px;"
        "  padding: 10px;"
        "  background-color: #B0B0B0;"
        "  color: white;"
        "}");
}
bool Page1::validateCredentials() {
    QString username = accountEdit->text();
    QString password = passwordEdit->text();
    QString position;
    QString dbType;
     QString dbName,pass;
     QString host; int port; QString user; QString sqlpassword;
    if (adminRadioButton->isChecked()) {
        position = "管理员";
    } else if (salesRadioButton->isChecked()) {
        position = "销售管理员";
    } else if (warehouseRadioButton->isChecked()) {
        position = "仓库管理员";
    } else if (financeRadioButton->isChecked()) {
        position = "财务管理员";
    }
    DatabaseManager& dbManager = DatabaseManager::instance();
    dbManager.loadDatabaseConfig(dbType);
    if(dbType=="QSQLITE"){
        dbManager.loadSqliteConfig(dbName);
        dbManager.connectToSqlite(dbName);
    }
    else if(dbType=="QMYSQL"){
        dbManager.loadMySQLConfig(host,port,dbName,user,sqlpassword);
        dbManager.connectToMySQL(host,port,dbName,user,sqlpassword);
        readConfigFile(dbType, dbName, host, port, user, pass);

    }
    return dbManager.checkAuthentication(username, password, position);
}


void Page1::openConnectionDialog() {
    ConnectionDialog dialog(this);
    connect(&dialog, &ConnectionDialog::connectionStatusChanged, this, &Page1::updateConnectionButtonColor);

    if (dialog.exec() == QDialog::Accepted) {
        DatabaseManager &dbManager = DatabaseManager::instance();
        bool connected = false;

        if (dialog.localConnectionRadioButton->isChecked()) {//本地
            QString localDbName = dialog.getLocalDbName();
            dbManager.saveSqliteConfig(localDbName);
            if (dbManager.connectToSqlite(localDbName)) {
                connected = true;
            } else {
                //qDEbug() << "Failed to connect to local database.";
            }
        } else if (dialog.remoteConnectionRadioButton->isChecked()) {//远程
            QString host = dialog.getHost();
            int port = dialog.getPort().toInt();
            QString remoteDbName = dialog.getRemoteDbName();
            QString username = dialog.getUsername();
            QString password = dialog.getPassword();
            dbManager.saveDatabaseConfig("QMYSQL",host,port,remoteDbName,username,password);
            dbManager.connectToMySQL(host,port,remoteDbName,username,password);
        }
    }
}

void Page1::updateConnectionButtonColor(bool isFilled) {
    connectionButton->setStyleSheet(isFilled ?
        "QPushButton {"
        "  font-size: 18px;"
        "  font-weight: bold;"
        "  border: 2px solid #E0E0E0;"
        "  border-radius: 20px;"
        "  padding: 10px;"
        "  background-color: #0093D1;"
        "  color: white;"
        "}" :
        "QPushButton {"
        "  font-size: 18px;"
        "  font-weight: bold;"
        "  border: 2px solid #E0E0E0;"
        "  border-radius: 20px;"
        "  padding: 10px;"
        "  background-color: lightblue;"
        "  color: white;"
        "}"
    );
}
void Page1::readConfigFile(QString &dbType, QString &dbName, QString &host, int &port, QString &user, QString &pass) {
    QSettings settings("dbconfig.ini", QSettings::IniFormat);
    dbType = settings.value("database/type").toString();
    dbName = settings.value("database/dbName").toString();
    host = settings.value("database/host").toString();
    port = settings.value("database/port").toInt();
    user = settings.value("database/user").toString();
    pass = settings.value("database/password").toString();
}

void Page1::clearInputFields() {
    // 清除输入栏中的数据
    accountEdit->clear();
    passwordEdit->clear();

    // 清除单选按钮的选中状态
    roleGroup->setExclusive(false); // 允许取消所有单选按钮的选中状态
    adminRadioButton->setChecked(false);
    salesRadioButton->setChecked(false);
    warehouseRadioButton->setChecked(false);
    financeRadioButton->setChecked(false);
    roleGroup->setExclusive(true); // 恢复单选按钮的互斥状态

    // 恢复登录按钮的颜色到未输入信息的状态
    loginButton->setStyleSheet("QPushButton {"
                               "  font-size: 24px;"
                               "  font-weight: bold;"
                               "  border: 2px solid #E0E0E0;"
                               "  border-radius: 20px;"
                               "  padding: 10px;"
                               "  background-color: #B0B0B0;"
                               "  color: white;"
                               "}");
    loginButton->setEnabled(false);
}
